<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" labelWidth="85" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- :fetchapi="fetchApi" -->
    <!-- :params="fetchParams" -->
    <!-- :datakey="'records'" -->
    <!-- columnsRef="inOutReport11" -->
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="part_report_revenueAndExpenditure_portrait"
      :params="fetchParams"
      :dataSource="tableListData"
      :onColumnsChange="columns => (this.columns = columns)"
      :isSelectColumn="false"
      :onSyncTableData="tableHandle"
      :mergeCellMethod="mergeCell"
      :onSummationChange="handleTableSummation"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" icon="el-icon-printer" @click="handlePrint">打印</el-button>
        <el-button size="small" type="primary" icon="el-icon-upload2" :loading="exportLoading" @click="handleExport">导出</el-button>
      </template>
    </FilterTable>

    <!-- 打印组件 -->
    <BasePrint
      ref="print"
      :data="printData"
      :printerType="printParams.vPrintType == 99901002 ? 'stylus' : 'laser'"
      :alwaysPrint="printParams.vPageType == 99911002 ? true : false"
      :printCopies="printParams.nPages || 1"
      :direction="printParams.vPageDirection == 99921001 ? 'horizontal' : 'vertical'"
      :directPrint="printParams.vDirectPrint == 1 ? true : false"
      :isDuplex="printParams.vBothPrint == 1 ? true : false"
      template="part/report/templateRevenueAndExpenditurePortrait"
    />
  </div>
</template>

<script>
/*
 *
 * 材料收支汇总--  纵向报表.
 */

import { authority } from '@/utils/authMixin';
import { materialqueryzInfo, titleHead, exportQueryz } from '@/api/part/report/revenueAndExpenditure';
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { getUser } from '@/assets/js/auth';
import { exportExcelFile, notifyAction } from '@/utils';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'clszhzzxbb',
  components: {},
  mixins: [authority, dictionary],
  props: {
    // ptype: String
  },
  data() {
    this.zdata = [];
    return {
      visible: false,
      topFilterList: this.createTopFilters(),
      fetchApi: materialqueryzInfo,
      columns: this.createTableColumns(),
      exportLoading: false,
      fetchParams: { date: moment().format('YYYY-MM') },
      formData: {}, // 向子组件传数据的数组
      tableData: [], // 表单数据
      tableListData: [], // table列表数据
      nowDate: moment().format('YYYY-MM'),
      tableHeadData: [], // 表头数据
      printData: {}, // 打印数据
      printParams: {} // 打印参数
    };
  },
  computed: {
    ptype() {
      // console.log(this.$route.meta.ptype, 1283281838);

      return this.$route.meta.ptype;
    } // 模块区分
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.concatNewTableColumns();
    this.topFilterList.find(item => item.fieldName == 'date').initialValue = moment().format('YYYY-MM');
    this.queryPrintParams();
    // console.log(this.ptype, '模块');
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'DATE',
          label: '查询日期',
          fieldName: 'date',
          initialValue: '',
          valueFormat: 'yyyy-MM',
          dateType: 'month'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '',
          dataIndex: 'name',
          width: 40
        },
        {
          title: '配件分类',
          dataIndex: 'rowData',
          width: 130,
          align: 'center'
        }
      ];
    },
    // 搜索
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { ptype: this.ptype ? this.ptype : null });
      console.log(this.fetchParams, '查询参数');
      this.concatNewTableColumns();
      // this.queryTableData();
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    // table动态回调函数
    tableHandle(val) {
      this.tableData = val;
      console.log(this.tableData, 'table数据改变');
    },

    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 拼接表头
    async concatNewTableColumns() {
      this.tableHeadData = [];
      this.columns = this.createTableColumns();
      this.$refs.table.START_LOADING();
      let resData = await titleHead(this.fetchParams);
      console.log(resData.data);
      this.tableHeadData = resData.data;
      let data = resData.data.map((item, index) => ({ title: this.createDictText(item, 8106), dataIndex: 'a' + index, precision: 2, summation: false }));
      data.push({ title: '合计', dataIndex: 'sumAmount', precision: 2 });
      this.tableHeadData.push('合计');
      this.columns = this.columns.concat(data);
      this.$nextTick(() => {
        this.queryTableData(data);
      });
    },

    // 插叙table数据
    async queryTableData(data) {
      this.zdata = await materialqueryzInfo(this.fetchParams);
      this.$refs.table.EXECUTE_DELETE(this.tableData);
      // let abd = data[0].dataIndex + '_ALLIN';
      try {
        this.$refs.table.EXECUTE_INSERT([
          { rowData: '期初', ...this.getValueByCode('OPEN_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('OPEN_AMOUNT', this.zdata.data) },
          { name: '收入', rowData: '采购收入', ...this.getValueByCode('BUY_IN_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('BUY_IN_AMOUNT', this.zdata.data) },
          { rowData: '借进收入', ...this.getValueByCode('ALLOCATE_IN_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('ALLOCATE_IN_AMOUNT', this.zdata.data) },
          { rowData: '盘点收入', ...this.getValueByCode('INVENTORY_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('INVENTORY_AMOUNT', this.zdata.data) },
          { rowData: '收入合计', ...this.getValueByCode('TOTAL_INCOME', this.zdata.data), sumAmount: this.sumRowAmount('TOTAL_INCOME', this.zdata.data) },
          { name: '支出', rowData: '首保支出', ...this.getValueByCode('FIRST_GUARANTEE', this.zdata.data), sumAmount: this.sumRowAmount('FIRST_GUARANTEE', this.zdata.data) },
          { rowData: '索赔支出', ...this.getValueByCode('CLAIMANT', this.zdata.data), sumAmount: this.sumRowAmount('CLAIMANT', this.zdata.data) },
          { rowData: '保养支出', ...this.getValueByCode('MAINTENANCE', this.zdata.data), sumAmount: this.sumRowAmount('MAINTENANCE', this.zdata.data) },
          { rowData: '小修支出', ...this.getValueByCode('MINOR_REPAIR', this.zdata.data), sumAmount: this.sumRowAmount('MINOR_REPAIR', this.zdata.data) },
          { rowData: '大修支出', ...this.getValueByCode('OVERHAUL', this.zdata.data), sumAmount: this.sumRowAmount('OVERHAUL', this.zdata.data) },
          { rowData: '事故支出', ...this.getValueByCode('ACCIDENT', this.zdata.data), sumAmount: this.sumRowAmount('ACCIDENT', this.zdata.data) },
          { rowData: '返工支出', ...this.getValueByCode('REWORK', this.zdata.data), sumAmount: this.sumRowAmount('REWORK', this.zdata.data) },
          { rowData: '年审支出', ...this.getValueByCode('ANNUAL_REVIEW', this.zdata.data), sumAmount: this.sumRowAmount('ANNUAL_REVIEW', this.zdata.data) },
          { rowData: '其它支出', ...this.getValueByCode('OTHER_OUT_SALE_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('OTHER_OUT_SALE_AMOUNT', this.zdata.data) },
          { rowData: '销售', ...this.getValueByCode('SALE_OUT_COST_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('SALE_OUT_COST_AMOUNT', this.zdata.data) },
          { rowData: '维修销售小计支出', ...this.getValueByCode('SUBTOTAL_MAINTENANCE_SALES', this.zdata.data), sumAmount: this.sumRowAmount('SUBTOTAL_MAINTENANCE_SALES', this.zdata.data) },
          { rowData: '内修支出', ...this.getValueByCode('INSURANCE', this.zdata.data), sumAmount: this.sumRowAmount('INSURANCE', this.zdata.data) },
          // { rowData: '内部领用支出', ...this.getValueByCode('INNER_OUT_SALE_AMOUNT', this.zdata.data) },
          { rowData: '内部领用支出', ...this.getValueByCode('INNER_OUT_COST_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('INNER_OUT_COST_AMOUNT', this.zdata.data) },
          // { rowData: '还出支出', ...this.getValueByCode('ALLOCATE_OUT_SALE_AMOUNT', this.zdata.data) },
          { rowData: '还出支出', ...this.getValueByCode('ALLOCATE_OUT_COST_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('ALLOCATE_OUT_COST_AMOUNT', this.zdata.data) },
          { rowData: '兑奖出库支出', ...this.getValueByCode('AWARD_OUT_COST_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('AWARD_OUT_COST_AMOUNT', this.zdata.data) },
          { rowData: '其它小计支出', ...this.getValueByCode('OTHER_SUBTOTALS', this.zdata.data), sumAmount: this.sumRowAmount('OTHER_SUBTOTALS', this.zdata.data) },
          { rowData: '支出合计支出', ...this.getValueByCode('TOTAL_EXPENDITURE', this.zdata.data), sumAmount: this.sumRowAmount('TOTAL_EXPENDITURE', this.zdata.data) },
          { rowData: '结存', ...this.getValueByCode('CLOSE_AMOUNT', this.zdata.data), sumAmount: this.sumRowAmount('CLOSE_AMOUNT', this.zdata.data) }
        ]);
      } catch (err) {
        console.err(err);
        this.$refs.table.STOP_LOADING();
      }
      this.$refs.table.STOP_LOADING();
    },
    // 根据字段名称取值字段
    getValueByCode(code, data) {
      let obj = {};
      data.map((item, index) => {
        let key = 'a' + index;
        obj[key] = item[code];
      });
      return obj;
    },
    // 计算合计金额
    sumRowAmount(code, data) {
      let total = 0;
      data.map(item => {
        total += item[code];
      });
      return total;
    },
    // 合并行或列
    mergeCell({ row, column, rowIndex, columnIndex }) {
      // if (rowIndex <= 1) {
      //   if (columnIndex === 1) {
      //     return {
      //       colspan: 2,
      //       rowspan: 1
      //     };
      //   }
      // }
      if (columnIndex === 1) {
        if (rowIndex === 0) {
          return {
            rowspan: 1,
            colspan: 2
          };
        } else if (rowIndex === 22) {
          return {
            rowspan: 1,
            colspan: 2
          };
        }
      }

      if (columnIndex === 0) {
        if (rowIndex === 0) {
          return {
            rowspan: 1,
            colspan: 0
          };
        } else if (rowIndex === 1) {
          return {
            rowspan: 4,
            colspan: 1
          };
        } else if (rowIndex === 5) {
          return {
            rowspan: 17,
            colspan: 1
          };
        } else {
          return [0, 0];
        }
      }
    },
    // 点击打印
    handlePrint() {
      if (this.zdata.data.length) {
        this.printData.tableHeadList = this.tableHeadData.map(item => this.createDictText(item, '8106')); // 表头
        let rowDataObj = {
          OPEN_AMOUNT: [], // 期初
          BUY_IN_AMOUNT: [], // 采购收入
          ALLOCATE_IN_AMOUNT: [], // 借进收入
          PROFIT_IN_AMOUNT: [], // 盘点收入
          TOTAL_INCOME: [], // 收入合计
          FIRST_GUARANTEE: [], // 首保支出
          CLAIMANT: [], // 索赔支出
          MAINTENANCE: [], // 保养支出
          MINOR_REPAIR: [], // 小修支出
          OVERHAUL: [], // 大修支出
          ACCIDENT: [], // 事故支出
          REWORK: [], // 返工支出
          ANNUAL_REVIEW: [], // 年审支出
          OTHER_OUT_SALE_AMOUNT: [], // 其他支出
          SALE_OUT_COST_AMOUNT: [], // 销售
          SUBTOTAL_MAINTENANCE_SALES: [], // 维修销售小计支出
          INSURANCE: [], // 内修支出
          INNER_OUT_COST_AMOUNT: [], // 内部领用支出
          ALLOCATE_OUT_COST_AMOUNT: [], // 还出支出
          AWARD_OUT_COST_AMOUNT: [], // 兑奖出库支出
          OTHER_SUBTOTALS: [], // 其他小计支出
          TOTAL_EXPENDITURE: [], // 支出合计支出
          CLOSE_AMOUNT: [] // 结存
        };
        this.zdata.data.map(item => {
          rowDataObj.OPEN_AMOUNT.push(item.OPEN_AMOUNT);
          rowDataObj.BUY_IN_AMOUNT.push(item.BUY_IN_AMOUNT);
          rowDataObj.ALLOCATE_IN_AMOUNT.push(item.ALLOCATE_IN_AMOUNT);
          rowDataObj.PROFIT_IN_AMOUNT.push(item.PROFIT_IN_AMOUNT);
          rowDataObj.TOTAL_INCOME.push(item.TOTAL_INCOME);
          rowDataObj.FIRST_GUARANTEE.push(item.FIRST_GUARANTEE);
          rowDataObj.CLAIMANT.push(item.CLAIMANT);
          rowDataObj.MAINTENANCE.push(item.MAINTENANCE);
          rowDataObj.MINOR_REPAIR.push(item.MINOR_REPAIR);
          rowDataObj.OVERHAUL.push(item.OVERHAUL);
          rowDataObj.ACCIDENT.push(item.ACCIDENT);
          rowDataObj.REWORK.push(item.REWORK);
          rowDataObj.ANNUAL_REVIEW.push(item.ANNUAL_REVIEW);
          rowDataObj.OTHER_OUT_SALE_AMOUNT.push(item.OTHER_OUT_SALE_AMOUNT);
          rowDataObj.SALE_OUT_COST_AMOUNT.push(item.SALE_OUT_COST_AMOUNT);
          rowDataObj.SUBTOTAL_MAINTENANCE_SALES.push(item.SUBTOTAL_MAINTENANCE_SALES);
          rowDataObj.INSURANCE.push(item.INSURANCE);
          rowDataObj.INNER_OUT_COST_AMOUNT.push(item.INNER_OUT_COST_AMOUNT);
          rowDataObj.ALLOCATE_OUT_COST_AMOUNT.push(item.ALLOCATE_OUT_COST_AMOUNT);
          rowDataObj.AWARD_OUT_COST_AMOUNT.push(item.AWARD_OUT_COST_AMOUNT);
          rowDataObj.OTHER_SUBTOTALS.push(item.OTHER_SUBTOTALS);
          rowDataObj.TOTAL_EXPENDITURE.push(item.TOTAL_EXPENDITURE);
          rowDataObj.CLOSE_AMOUNT.push(item.CLOSE_AMOUNT);
        });
        // 注入合计数据
        for (let item in rowDataObj) {
          rowDataObj[item].push(this.sumRowAmount(item, this.zdata.data).toFixed(2));
        }
        // 添加底部合计数据
        // rowDataObj.summationArr = this.summationArr;

        this.printData = Object.assign(this.printData, rowDataObj);

        this.printData.createBy = getUser();
        this.printData.date = this.topFilterList.find(item => item.fieldName == 'date').initialValue;
        this.$refs.print.EXCUTE_PRINT();
      } else {
        notifyAction('请先查询数据', 'warning');
      }
    },
    handleExport() {
      this.exportLoading = true;
      let data = {
        date: this.topFilterList.find(item => item.fieldName == 'date').initialValue
      };
      exportQueryz(data).then(res => {
        exportExcelFile(res, '材料收支汇总');
        this.exportLoading = false;
      });
    },
    // 合计数据变化
    handleTableSummation(e) {
      this.summationArr = e.map(item => item.value);
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJCLSZ'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped></style>
